package com.lun.blog.service.impl;

import com.lun.blog.repostory.PictureRepository;
import com.lun.blog.pojo.Picture;
import com.lun.blog.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

@Service
public class PictureServiceImpl implements PictureService {

    @Autowired
    private PictureRepository pictureRepository;

    @Override
    public Picture getPicture(Long id) {
        return pictureRepository.getOne(id);
    }

    @Override
    @Transactional
    public Picture savePicture(Picture picture) {
        if(picture.getId()!=null){
            picture.setUpdateTime(new Date());
        }else {
            picture.setCreateTime(new Date());
            picture.setUpdateTime(new Date());
        }
        return pictureRepository.save(picture);
    }

    @Override
    @Transactional
    public boolean deletePicture(Long id) {
        Picture picture = pictureRepository.getOne(id);
        if(ObjectUtils.isEmpty(picture)||picture==null){
            return false;
        }
        pictureRepository.delete(picture);
        return true;
    }

    @Override
    public Page<Picture> listPage(Pageable pageable) {
        return pictureRepository.findAll(pageable);
    }

    @Override
    public Picture findByPictureName(String pictureName) {
        return pictureRepository.findByPictureName(pictureName);
    }

    @Override
    public List<Picture> findAll() {
        return pictureRepository.listPicture();
    }
}
